package itsm.isperp.framework.message;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.message.domain.IMessagePacket;
import itsm.isperp.framework.message.domain.MessageType;
import itsm.isperp.framework.message.service.MessageQueueService;
import itsm.isperp.framework.template.Template;
import itsm.isperp.framework.template.TemplateException;
import itsm.isperp.module.entity.app.AppMessage;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * 消息队列,现阶段只支持持久化队列
 * 
 * @author lizx
 * @date 2013-8-27
 * 
 */
public final class MessageQueue {

	/**
	 * 添消息包加到发送队列
	 * 
	 * @param msssage
	 *            消息包 {@link IMessagePacket}
	 */
	public static final void addToMessageQuery(IMessagePacket msssage) {
		((MessageQueueService) ContextHolder.getSpringBean("appMessageService"))
				.addToMessageQuery(msssage);
	}

	/**
	 * 添加消息包集合到发送队列
	 * 
	 * @param msssage
	 *            消息包集合 {@link IMessagePacket}
	 */
	public static final void addToMessageQuery(
			Collection<IMessagePacket> messages) {
		MessageQueueService ms = ContextHolder
				.getSpringBean("appMessageService");

		ms.addToMessageQuery(messages);

	}

	public static final void generalAndAllToMeessageList(final String sourceId,
			final String messageType, final Map<String, IUser> mapUsers,
			String title, String content, List<IMessagePacket> messageList,
			Template template) {

		if (StringUtils.isNotEmpty(messageType)) {
			String[] messageTypes = messageType.split(",");
			for (int i = 0; i < messageTypes.length; i++) {
				String mType = messageTypes[i];
				Set<String> sets = mapUsers.keySet();
				for (String obj : sets) {
					IUser u = mapUsers.get(obj);
					IMessagePacket pack = new AppMessage();
					pack.setSourceId(sourceId);
					template.getContext().put("bpmNextUserBean", u);
					try {
						template.setSource(title);
						title = template.render();
					} catch (TemplateException e) {
						// log..
						break;
					}

					template.setSource(content);
					try {
						content = template.render();
					} catch (TemplateException e) {
						// log..
						break;
					}

					pack.setTitle(title);
					pack.setContent(content);
					pack.setReceiver(u.getUsername());
					pack.setReceiverAddress((MessageType.EMAIL.equals(mType)) ? u
							.getEmail() : (MessageType.SMS.equals(mType)) ? u
							.getMobile() : u.getUsername());
					pack.setMessageType(mType);
					pack.setSender("admin");
					messageList.add(pack);
				}

			}
		}
	}
}
